<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
    <head>        
        <!-- META SECTION -->
        <title>权限管理</title>            
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        
        <link rel="icon" href="favicon.ico" type="image/x-icon" />
        <!-- END META SECTION -->
        
        <!-- CSS INCLUDE -->        
        
		<link rel="stylesheet" href="${ctx}/rs/js/zTree/css/zTreeStyle/metro.css"/>
        <link rel="stylesheet" href="${ctx}/rs/css/bootstrap-table.css" />
        <link rel="stylesheet" href="${ctx}/rs/css/main.css" />
        <link id="theme" rel="stylesheet" href="${ctx}/rs/joli/css/theme-default.css" />
        
        <!-- EOF CSS INCLUDE -->                                    
    </head>
    <body>
        <!-- START PAGE CONTAINER -->
        <div class="page-container">
        	<!-- 引入左菜单部分 -->
            <jsp:include page="../joli/menu.jsp"></jsp:include>
            
            <!-- START PAGE CONTENT -->
            <div class="page-content">
                <jsp:include page="../joli/top.jsp"></jsp:include>
                
                <!-- START BREADCRUMB -->
                <ul class="breadcrumb">
                    <li><a href="#">系统管理</a></li>                    
                    <li class="active">权限管理 </li>
                </ul>
                <!-- END BREADCRUMB -->   
                
                
                <!-- PAGE CONTENT WRAPPER -->
                <div class="page-content-wrap">
                	<div class="row">
	            		<div class="col-xs-12">
	            			<div id="toolbar">
								<shiro:hasPermission name="permission:add">
									<button class="btn btn-info srt-btn btn-sm icon-adds" onclick="add()">新增</button>
								</shiro:hasPermission>
								<shiro:hasPermission name="permission:edit">
									<button class="btn btn-success srt-btn btn-sm icon-editor" onclick="edit()">编辑</button>
								</shiro:hasPermission>
								<shiro:hasPermission name="permission:delete"> 
									<button class="btn btn-danger srt-btn btn-sm icon-delt" onclick="removeData()">删除</button>
								</shiro:hasPermission>
								<shiro:hasPermission name="permission:sort">
								    <button class="btn btn-success srt-btn btn-sm icon-save" onclick="saveData()">保存排序</button>
								</shiro:hasPermission>
								<div class="fr pb10">
								    权限菜单：
								  <div class="treepost">
								  <input type="hidden" id="pId" name="pId"/>
								  <input type="text" readonly="readonly" class="treeput" id="key" onclick="showMenu();"/>
								  <div id="menuCase" class="menuContent" style="display:none; position: absolute; z-index:9999">
						              <ul id="menuTree" class="ztree" style="width:170px;overflow:auto;z-index:9999;background: white;border: 1px lightgrey solid;"></ul>
					              </div>
					              </div>
								  <button class="btn btn-primary btn-sm srt-btn active" onclick="refresh()">搜索</button>
							    </div>
							</div>
							<table id="table" cellpadding="0" cellspacing="0" data-toggle="table" data-toolbar="#toolbar"
								data-url="${ctx}/permission/page.htm"
								data-cache="false"
								data-pagination="true" 
								data-side-pagination="server"
								data-page-list="[10, 20, 50, 100]"
								data-page-size="20"  
								data-query-params="queryParams">
								<thead>
									<tr class="tab-th">
										<th data-field="state" data-checkbox="true"></th>
										<th data-field="id">编号</th>
										<th data-field="permName">权限名称</th>
										<th data-field="permCode">权限代码</th>
										<th data-field="permLevel">权限级别</th>
										<th data-field="parentId">上级编号</th>
										<th data-field="authorizName">授权名称</th>
										<th data-field="ranking" data-editable="true">排序(可编辑)</th>
										<th data-field="enables" data-formatter="enablesFormatter">状态</th>
										<th data-field="createDate" data-formatter="timeFormatter">创建时间</th>
						                <th data-field="action" data-formatter="actionFormatter">操作</th>
									</tr>
								</thead>
							</table>
	            		</div>
	            	</div>
            	</div>
		</div>
	</body>
	
	<!-- 引入所有joli的脚本 -->
	<jsp:include page="../joli/scripts.jsp"></jsp:include>
	<!-- 引入页面需要的脚本 -->
	<script type="text/javascript" src="${ctx}/rs/js/bootstrapQ.min.js"></script>
	<script src="${ctx}/rs/js/zTree/js/jquery.ztree.all-3.5.min.js"></script>
	<script src="${ctx}/rs/js/bootstrap-table.js"></script>
	<script src="${ctx}/rs/js/bootstrap-table-zh-CN.js"></script>
	<script src="${ctx}/rs/js/jquery.formatDate.js"></script>
	<script src="${ctx}/rs/js/my97DatePicker/WdatePicker.js"></script>
	<script type="text/javascript" src="${ctx}/rs/js/session-out-error.js"></script>
	
	<script>
		activeMenu($("#menu_sys_1"));
        var $table = $('#table');
        
        $table.on('click-row.bs.table', function (e, row, $element) {
	    	$table.bootstrapTable('uncheckAll');
	    	$table.bootstrapTable('check', $element.index());
        });
        
        $table.bootstrapTable({
            height: getHeight()
        });
	    
        //获取分辨率高度
	    function getHeight() {
	        return window.screen.height - 308;
	    }
      //ztree初始化
		var setting = {
			view: {
				dblClickExpand: false
			},
			data: {
				key: {
//	 				children: "permissions",
					name: "permName",
					url: "#"
				},
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "parentId"
				}
			},
			callback: {
				onClick: onClick
			}
		};
      
		$.ajax({
            url: "${ctx}/permission/zTree",
            success: function (data) {
            	var zNodes = eval(data);
            	$.fn.zTree.init($("#menuTree"), setting, zNodes);
            },
            error: function () {
            	bootstrapQ.msg({
					    msg  : '树状下拉列表加载失败！',
					    type : 'danger',
					    time : 2000
					});
            }
        });

		function onClick(e, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("menuTree"),
			nodes = zTree.getSelectedNodes(),
			d = "",
			v = "";
			for (var i=0, l=nodes.length; i<l; i++) {
				d = nodes[i].id;
				v = nodes[i].permName;
			}
		    $("#pId").attr("value", d);
		    $("#key").attr("value", v);
			hideMenu();
		}

		function showMenu() {
			var cityObj = $("#key");
			var cityOffset = $("#key").offset();
			$("#menuCase").css({left:'0' + "px", top:'32' + "px"}).slideDown("fast");

			$("body").bind("mousedown", onZBodyDown);
		}
		
		function hideMenu() {
			$("#menuCase").fadeOut("fast");
			$("body").unbind("mousedown", onZBodyDown);
		}
		
		function onZBodyDown(event) {
			if (!(event.target.id == "menuCase" || $(event.target).parents("#menuCase").length>0)) {
				hideMenu();
			}
		}
        
	    //初始化刷新
	  function refresh(pageIndex,selectPage){
	    	if(!pageIndex && !selectPage){
	    		pageIndex = 0;
	    		selectPage = 0;
	    	}
	    	var parentId = $("#pId").val();
	    	var pageSize = $table.bootstrapTable('getOptions').pageSize;
	    	pageIndex=pageIndex*pageSize;
	    	$table.bootstrapTable('refresh', {
	    		silent: true,
	    		cache : false,
                url: '${ctx}/permission/page.htm',
                query: {
                	parentId : parentId,
                	pageIndex : pageIndex,
    				pageSize : pageSize
    			}
            });
	    	$table.bootstrapTable('selectPage', selectPage);
	    }
	    
	    function add() {
	    	var pageNumber = $table.bootstrapTable('getOptions').pageNumber;
			var pageIndex = pageNumber - 1;
			bootstrapQ.dialog({
				url : '${ctx}/permission/add.htm',
				title : '新增权限',
				width: '720px',
				close : 'true',
				hidebtn : 'true'
			},function(){
				//回调触发关闭窗口
				$("#bsmodal").modal("hide");
				refresh(pageIndex,pageNumber);
			});
		};
		
		function edit() {
			var pageNumber = $table.bootstrapTable('getOptions').pageNumber;
			var pageIndex = pageNumber - 1;
			var rows = $table.bootstrapTable('getSelections');
			if (rows.length == 1) {
				bootstrapQ.dialog({
					url : "${ctx}/permission/edit.htm?id="+ rows[0].id,
					title : "编辑权限",
					width: '720px',
					close : 'true',
					hidebtn : 'true'
				},function(){
					//回调触发关闭窗口
					$("#bsmodal").modal("hide");
					refresh(pageIndex,pageNumber);
				});
			}else{
				bootstrapQ.alert("请选中一条记录");
			}
        }
		
		function removeData() {
			var pageNumber = $table.bootstrapTable('getOptions').pageNumber;
			var pageIndex = pageNumber - 1;
			var rows = $table.bootstrapTable('getSelections');
			var len=$("#table tbody").find("tr").length;
	        if(len==rows.length){
		        pageIndex = pageIndex - 1;
		    }
            if(rows.length > 0){
            	bootstrapQ.confirm('确定删除选中记录（非超级管理员请慎重操作）？',function(){
            		var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
                        return row.id;
                    });
                    $.ajax({
                        url: "${ctx}/permission/delete.htm?ids="+ids,
                        success: function (text) {
                        	bootstrapQ.msg({
     						    msg  : '删除成功！',
     						    type : 'success',
     						    time : 2000
     						});
                        	refresh(pageIndex,pageNumber);
                        },
                        error: function () {
                        	bootstrapQ.msg({
     						    msg  : '删除失败！',
     						    type : 'danger',
     						    time : 2000
     						});
                        	refresh(pageIndex,pageNumber);
                        }
                    });
    			},null);
            }else{
            	bootstrapQ.alert("请选择要删除的记录！");
            }
        }
		
	    function queryParams(params) {
			return {
				pageIndex : params.offset,
				pageSize : params.limit
			};
		}
	    
	    function enablesFormatter(value, row, index){
	    	if (value == 0){
				return "<span class='label label-danger'>禁用</span>";
			}
			else{
				return "<span class='label label-success'>启用</span>";
			}
		}
 
		function timeFormatter(value, row, index){
			 if(value){
				 return $.formatDate("yyyy-MM-dd HH:mm:ss", new Date(value));
			 }
			 return "--";
		}
		
		function actionFormatter(value, row, index) {
			var bnt = "", status;
            if(row.enables == 1){
            	bnt = "禁用";
            	status = 0;
            }else{
            	bnt = "启用";
            	status = 1;
            }
            return '<shiro:hasPermission name="permission:status"><a href="javascript:updateStatus(\'' + row.id + '\','+status+')">'+bnt+'</a></shiro:hasPermission>';
		}
		
		function updateStatus(id,status){
			var pageNumber = $table.bootstrapTable('getOptions').pageNumber;
			var pageIndex = pageNumber - 1;
			$.ajax({
                url: "${ctx}/permission/updateStatus.htm",
                data: { 
		        	id: id,
		        	enables : status
		        },
		        type: "post",
                success: function (text) {
                	bootstrapQ.msg({
						    msg  : '更改状态成功！',
						    type : 'success',
						    time : 2000
						});
                	refresh(pageIndex,pageNumber);
                },
                error: function () {
                	bootstrapQ.msg({
						    msg  : '更改状态失败！',
						    type : 'danger',
						    time : 2000
						});
                	refresh(pageIndex,pageNumber);
                }
            });
		}
		
		
		function saveData() {
			var pageNumber = $table.bootstrapTable('getOptions').pageNumber;
			var pageIndex = pageNumber - 1;
			var data = $table.bootstrapTable('getData');
			if(data.length <= 0){
				bootstrapQ.alert("暂未数据保存！");
	        	return false;
			}
		    $.ajax({
		        url: "${ctx}/permission/saveSort.htm",
		        data: { data: JSON.stringify(data) },
		        type: "post",
		        success: function (text) {
		        	bootstrapQ.msg({
						    msg  : '操作成功！',
						    type : 'success',
						    time : 2000
						});
		        	refresh(pageIndex,pageNumber);
		        },
		        error: function (jqXHR, textStatus, errorThrown) {
		        	bootstrapQ.msg({
					    msg  : '操作失败！',
					    type : 'danger',
					    time : 2000
					});
		        	refresh(pageIndex,pageNumber);
		        }
		    });
		}
	</script>
</body>
</html>